package logproc

import (
	"starsine.cn/appTpl/cmn/config/aconf"
	. "starsine.cn/appTpl/cmn/defs"
	"starsine.cn/appTpl/cmn/logs"
	"starsine.cn/appTpl/svclog/src/logproc/logbuff"
	"starsine.cn/appTpl/svclog/src/logproc/logbuffmng"
)

type LogProc struct {
	buffSize int
	buff     *logbuff.LogBUff

	appCtxt *AppContext
}

func CreateLogProc(appCtxt *AppContext) *LogProc {
	p := new(LogProc)

	p.buffSize = aconf.GetInt("SvcLog.BuffSize", 1000, aconf.WithENV("svclog_buffsize"))
	p.buff = logbuff.CreateLogBUff(appCtxt, p.buffSize, run)

	p.appCtxt = appCtxt

	return p
}

func (p *LogProc) Close() {
	p.buff.Close()
	p.buff = nil
}

func (p *LogProc) GetLogBuff() *logbuff.LogBUff {
	return p.buff
}

func run(p *logbuff.LogBUff) {
	logs.Infof("LogProc.run routine start")
	p.AppContext().Wg.Add(1)
	defer func() {
		logs.Warnf("LogProc.run routine exit")
		p.AppContext().Wg.Done()
	}()

	for {
		select {
		case line := <-p.OutSync():
			is := logbuffmng.Get(line.InstanceID)
			is.In(line)

		case <-p.Quit():
			logs.WarnfWith("LogProc", "LogProc routine quit")
			return

		case <-p.AppContext().Ctx.Done():
			logs.Warnf("LogProc.run  routine ctxt done to quit")
			return
		}
	}
}
